package com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bidanet.bdcms.core.common.JsonParseTool;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.framework.cache.CacheManager;
import com.github.xuemingyu.springboot.acticitycloud.config.DingConfig;
import com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.DingTalkService;
import com.github.xuemingyu.springboot.acticitycloud.service.impl.BaseServiceImpl;
import com.taobao.api.ApiException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: xmy
 * \* Date: 2019/1/23
 * \* Time: 18:16
 * \
 */
@Service
public class DingTalkImpl extends BaseServiceImpl implements DingTalkService {
    @Autowired
    private DingConfig dingConfig;
    CacheManager cacheManager = CacheManager.getInstance().putListener();

    @Override
    public String getAccessToken() throws ApiException {
        String accessToken = "";
        Object accessObj = cacheManager.get("access_token");
        if (Objects.nonNull(accessObj) && !"".equals(accessObj)) {
            accessToken = accessObj.toString();
        } else {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(dingConfig.getAppKey());
            request.setAppsecret(dingConfig.getAppSecret());
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            if (response.getErrcode() == 0) {
                accessToken = response.getAccessToken();
                cacheManager.put("access_token", accessToken, 7000);
            } else {
                errorMsg(response.getErrmsg());
            }
        }
        return accessToken;
    }

    @Override
    public Map<String, String> loginByCode(String code) throws ApiException {
        checkString(code, "code不能为空");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(code);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response = client.execute(request, getAccessToken());
        if (response.getErrcode() != 0) {
            errorMsg(response.getErrmsg());
        }
        String userId = response.getUserid();
        OapiUserGetResponse responseByUserId = getResponseByUserId(userId);

        Map<String, String> map = new HashMap();

        cacheManager.put(userId, responseByUserId);

        map.put("userId", userId);
        map.put("url", responseByUserId.getAvatar());
        map.put("nickname", responseByUserId.getName());
        System.out.println("[dingdingcode]: code=" + code + "  accessToken=" + getAccessToken() + "  userId=" + userId);

        return map;
    }

    @Override
    public Map<String, String> pcLogin(String code) throws ApiException {
        checkString(code, "code不能为空");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(code);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response = client.execute(request, getAccessToken());
        if (response.getErrcode() != 0) {
            errorMsg(response.getErrmsg());
        }
        String userId = response.getUserid();
        OapiUserGetResponse responseByUserId = getResponseByUserId(userId);
        List<OapiUserGetResponse.Roles> roles = responseByUserId.getRoles();
        List<String> list = new ArrayList<>();
    /*   roles.forEach(q -> {
            if (q.getName().equals("WDYH")) {
                list.add(q.getName());
            }
        });*/
        Map<String, String> map = new HashMap();
        //   if (list.size() > 0) {
        cacheManager.put(userId, responseByUserId);

        map.put("userId", userId);
        map.put("url", responseByUserId.getAvatar());
        map.put("nickname", responseByUserId.getName());
        System.out.println("[dingdingcode]: code=" + code + "  accessToken=" + getAccessToken() + "  userId=" + userId);
        //      }
        return map;
    }

    protected OapiUserGetResponse getResponseByUserId(String userId) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(userId);
        request.setHttpMethod("GET");
        OapiUserGetResponse response = client.execute(request, getAccessToken());
        return response;
    }

    @Override
    public OapiUserGetResponse getUserInfoByUserId(String userId) throws ApiException {
        checkString(userId, "userId不能为空");
        OapiUserGetResponse userInfo = (OapiUserGetResponse) cacheManager.get(userId);
        if (Objects.nonNull(userInfo)) {
            return userInfo;
        } else {
            OapiUserGetResponse responseByUserId = getResponseByUserId(userId);
            return responseByUserId;
        }
    }

    @Override
    public OapiChatCreateResponse createConversation(String name, String userId, List<String> userList) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/create");
        OapiChatCreateRequest request = new OapiChatCreateRequest();
        request.setName(name);
        request.setOwner(userId);
        if (Objects.nonNull(userList)) {
            request.setUseridlist(userList);
        } else {
            request.setUseridlist(Arrays.asList(userId));
        }
        request.setShowHistoryType(1L);
        OapiChatCreateResponse response = client.execute(request, getAccessToken());
        return response;
    }

    @Override
    public OapiChatUpdateResponse updateConversation(String chatId, String addUserId, String delUserId) throws ApiException {
        checkString(chatId, "chatId不能为空");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/update");
        OapiChatUpdateRequest request = new OapiChatUpdateRequest();
        request.setChatid(chatId);
        //request.setName("群名称1");
        //request.setOwner("userid1");
        if (StringUtils.isNotEmpty(addUserId)) {
            request.setAddUseridlist(Arrays.asList(addUserId));
        }
        if (StringUtils.isNotEmpty(delUserId)) {
            request.setDelUseridlist(Arrays.asList(delUserId));
        }
        OapiChatUpdateResponse response = client.execute(request, getAccessToken());
        return response;
    }

    @Override
    public OapiDepartmentListResponse getDepartmentList() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        request.setId("1");
        request.setHttpMethod("GET");
        OapiDepartmentListResponse response;
        response = client.execute(request, getAccessToken());
        if (response.getErrcode() != 0) {
            errorMsg(response.getErrmsg());
        }
        return response;
    }

    @Override
    public String getParentDepts(String userId) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list_parent_depts");
        OapiDepartmentListParentDeptsRequest request = new OapiDepartmentListParentDeptsRequest();
        request.setUserId(userId);
        request.setHttpMethod("GET");
        OapiDepartmentListParentDeptsResponse response = client.execute(request, getAccessToken());
        if (response.getErrcode() != 0) {
            errorMsg(response.getErrmsg());
        }
        JSONArray objects = JSONObject.parseArray(response.getDepartment());
        String dept = ",";
        for (int i = 0; i < objects.size(); i++) {
            String str = objects.get(i).toString();
            String b = str.substring(1, str.length() - 1);
            dept = dept + b + ",";
        }
        return dept;
    }

    @Override
    public List<Long> getUserDept(String userId) throws ApiException {
        OapiUserGetResponse user = getUserInfoByUserId(userId);
        if (user.getErrcode() != 0) {
            errorMsg(user.getErrmsg());
        }
        List<Long> dept = user.getDepartment();

        return dept;
    }

    @Override
    public String getDeptName(String userId) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list_parent_depts");
        OapiDepartmentListParentDeptsRequest request = new OapiDepartmentListParentDeptsRequest();
        request.setUserId(userId);
        request.setHttpMethod("GET");
        OapiDepartmentListParentDeptsResponse response = client.execute(request, getAccessToken());
        if (response.getErrcode() != 0) {
            errorMsg(response.getErrmsg());
        }
        JSONArray jsonArray = JSONObject.parseArray(response.getDepartment());
        List<String> deptList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String str = jsonArray.get(i).toString();
            String b = str.substring(1, str.length() - 1);
            String[] split = b.split(",");
            deptList.add(split[0]);
        }
        String name = "";
        for (int i = 0; i < deptList.size(); i++) {
            DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
            OapiDepartmentGetRequest request1 = new OapiDepartmentGetRequest();
            request1.setId(deptList.get(i));
            request1.setHttpMethod("GET");
            try {
                OapiDepartmentGetResponse response1 = client1.execute(request1, getAccessToken());
                name = name + response1.getName() + ",";
            } catch (ApiException e) {
                e.printStackTrace();
            }

        }
        return name.substring(0, name.length() - 1);

    }

    @Override
    public String getActivityOrgs(String orgs) throws ApiException {
        String[] split = orgs.split(",");
        String name = "";
        for (int i = 0; i < split.length; i++) {
            if (StringUtils.isNotEmpty(split[i])) {
                DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
                OapiDepartmentGetRequest request1 = new OapiDepartmentGetRequest();
                request1.setId(split[i]);
                request1.setHttpMethod("GET");
                OapiDepartmentGetResponse response1 = client1.execute(request1, getAccessToken());
                if (response1.getErrcode() != 0) {
                    errorMsg(response1.getErrmsg());
                }
                name = name + response1.getName() + ",";

            }
        }
        return name.substring(0, name.length() - 1);
    }

    @Override
    protected JpaRepository getDao() {
        return null;
    }
}
